﻿using Dynamicweb;
using Dynamicweb.Extensibility;
using System.Collections.Generic;

namespace dwblogengine2012.CustomModules.BlogPageTags
{
    public class BlogPageTags : PageTemplateExtender
    {
        public override void ExtendTemplate(Dynamicweb.Rendering.Template template)
        {
            var page = Dynamicweb.Content.Page.GetPageById(PageView.Page.ID);            
            if (page != null)
            {
                template.SetTag("Blog:Post.ActiveFrom", page.ActiveFrom);

                var tags = new List<string>();
                foreach (var tag in GetTags(page))
                {
                    tags.Add(GetTagLink(tag));
                }
                if (tags.Count > 0)
                {
                    template.SetTag("Blog:Post.Tags", string.Join(", ", tags));
                }

                var user = Dynamicweb.Modules.UserManagement.User.GetUserByID(page.UserEdit);
                if (user != null)
                {
                    template.SetTag("Blog:Post.AuthorName", user.Name);
                    template.SetTag("Blog:Post.AuthorEmail", user.Email);
                    template.SetTag("Blog:Post.AuthorEmailMD5", Base.MD5HashToString(user.Email));
                }
            }
        }

        protected List<string> GetTags(Dynamicweb.Content.Page post)
        {
            var tags = new List<string>();
            var r = new System.Text.RegularExpressions.Regex("\\s*,\\s*");
            var tokens = r.Split(post.Keywords.Trim());
            foreach (var token in tokens)
            {
                if (!string.IsNullOrWhiteSpace(token))
                {
                    tags.Add(token);
                }
            }
            return tags;
        }

        protected string GetTagUrl(string tag)
        {
            return Dynamicweb.Frontend.SearchEngineFriendlyURLs.GetFriendlyUrl(string.Format("/Default.aspx?tag={0}", System.Web.HttpContext.Current.Server.UrlEncode(tag)));
        }

        protected string GetTagLink(string tag, string text = null)
        {
            return string.Format("<a href='{0}'>{1}</a>", System.Web.HttpContext.Current.Server.HtmlEncode(GetTagUrl(tag)), System.Web.HttpContext.Current.Server.HtmlEncode(text != null ? text : tag));
        }
    }
}
